<script setup lang="ts">
import type { Dayjs } from 'dayjs'
import { computed, ref, watch, watchEffect } from 'vue'
import { px2remPx } from '@/utils/flexble'
import dayjs from 'dayjs'
import useFilterStore, {
  type UserItem,
  type ConsultanlItem,
  type UserTypeItem
} from '@/stores/filter'
import { client } from '@/utils/http'
import { cloneDeep, flattenDeep } from 'lodash-es'

const filterStore = useFilterStore()

const type = ref('1')

const visible = ref(false)

const searchKeyword = ref('')

const checkedList = ref<string[]>([])

const disabledDate = (current: Dayjs) => {
  return (
    current &&
    (current < dayjs(filterStore.dateOption?.startYmd) ||
      current > dayjs(filterStore.dateOption?.endYmd))
  )
}

const originOptions = ref<ConsultanlItem[]>([])

watchEffect(() => {
  originOptions.value = cloneDeep(filterStore.settingDataOptions) || []
})

const plainOptions = computed(() => {
  const options: UserTypeItem[] =
    originOptions.value.find(({ positionTypeId }) => positionTypeId === type.value)?.list || []
  const showOptions = options.map((option) => ({
    ...option,
    list: option.list.filter(({ userName }) =>
      userName.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }))
  // console.log(111111, showOptions)
  return showOptions
})

const targetOptions = ref<UserItem[]>([])

watch(
  type,
  () => {
    const options: UserTypeItem[] =
      originOptions.value.find(({ positionTypeId }) => positionTypeId === type.value)?.list || []

    targetOptions.value = flattenDeep(options.map((option) => option.list)).filter(
      ({ userId, checked }) => checked /* || checkedList.value.includes(userId)*/
    )

    checkedList.value = targetOptions.value.map(({ userId }) => userId)
  },
  { immediate: true }
)

watch(originOptions, () => {
  const options: UserTypeItem[] =
    originOptions.value.find(({ positionTypeId }) => positionTypeId === type.value)?.list || []
  targetOptions.value = flattenDeep(options.map((option) => option.list)).filter(
    ({ checked }) => checked
  )
  checkedList.value = targetOptions.value.map(({ userId }) => userId)
})

function userChange(option: UserItem) {
  // console.log('userChange', option)
  if (checkedList.value.includes(option.userId)) {
    checkedList.value = checkedList.value.filter((value) => value !== option.userId)
    option.checked = false
  } else {
    checkedList.value = [...checkedList.value, option.userId]
    option.checked = true
  }
  const options: UserTypeItem[] =
    originOptions.value.find(({ positionTypeId }) => positionTypeId === type.value)?.list || []
  const all = flattenDeep(options.map((option) => option.list)).filter(({ userId }) =>
    checkedList.value.includes(userId)
  )
  targetOptions.value = all
}

function clickDeleteTarget(target: UserItem) {
  console.log('clickDeleteTarget', target)
  target.checked = false

  targetOptions.value = targetOptions.value.filter(({ userId }) => target.userId !== userId)

  checkedList.value = checkedList.value.filter((value) => target.userId !== value)
}

const saveLoading = ref(false)

async function save() {
  const ymId = filterStore.settingDate?.format('YYYYMM')
  if (!originOptions.value.length) {
    visible.value = false
    return
  }
  if (!ymId || !originOptions.value.length) return
  saveLoading.value = true
  try {
    const res = await client<boolean>(
      '/saleCoreBoard/saveConsultantList',
      { ymId, list: originOptions.value },
      { method: 'POST' }
    )
    // console.log('saveConsultantList result', res)

    visible.value = !res
    if (res) {
      filterStore.consultantListUpdateNum += 1
      filterStore.getConsultantList()
    }
  } catch (error) {
    //
  } finally {
    saveLoading.value = false
  }
}
</script>

<template>
  <a-popover
    :open="visible"
    trigger="click"
    placement="bottomRight"
    color="#1d2865"
    overlayClassName="setting-container"
  >
    <a-button type="primary" class="button" @click="visible = true">
      人员设置
      <SvgIcon name="drop-arrow" :size="20" />
    </a-button>
    <template #content>
      <a-spin :spinning="saveLoading">
        <div class="setting" @click.stop>
          <header>
            <div class="title">人员设置</div>
            <div class="right">
              <a-select v-model:value="type" :style="`width: ${px2remPx(100)}px`" size="small">
                <template #suffixIcon>
                  <SvgIcon name="drop-arrow" :size="16" />
                </template>
                <a-select-option
                  v-for="option in originOptions"
                  :key="option.positionTypeId"
                  :value="option.positionTypeId"
                >
                  {{ option.positionTypeName }}
                </a-select-option>
              </a-select>
              <a-date-picker
                v-model:value="filterStore.settingDate"
                picker="month"
                format="M月"
                :inputReadOnly="true"
                :allowClear="false"
                :showToday="false"
                :disabled-date="disabledDate"
              >
                <template #suffixIcon>
                  <SvgIcon name="drop-arrow" :size="16" />
                </template>
              </a-date-picker>
              <SvgIcon name="close" :size="20" @click="visible = false" />
            </div>
          </header>
          <main>
            <div class="add-user">
              <div class="sticky">
                <div class="title">添加人员</div>
                <div class="item">
                  <a-input v-model:value="searchKeyword" placeholder="搜索" size="small" />
                </div>
              </div>
              <div class="list add-list">
                <template v-for="option in plainOptions" :key="option.positionId">
                  <div v-if="!searchKeyword" class="item header-title">
                    {{ option.positionName }}
                  </div>
                  <a-checkbox
                    v-for="userItem in option.list"
                    :key="userItem.userId"
                    :checked="checkedList.includes(userItem.userId)"
                    @change="userChange(userItem)"
                  >
                    {{ userItem.userName }}
                  </a-checkbox>
                </template>
              </div>
            </div>
            <div class="target-setting">
              <template v-if="type !== '3'">
                <div class="title sticky">目标设定</div>
                <div class="list">
                  <div class="target-item" v-for="target in targetOptions" :key="target.value">
                    <div class="label-target">
                      <div class="label">{{ target.userName }}</div>
                      <a-input
                        v-model:value="target.value"
                        placeholder="输入目标"
                        size="small"
                        type="number"
                      />
                    </div>
                    <SvgIcon
                      name="setting-delete"
                      class="setting-delete"
                      :size="16"
                      @click="clickDeleteTarget(target)"
                    />
                  </div>
                </div>
              </template>
            </div>
          </main>
          <footer>
            <a-button size="small" @click="visible = false">取消</a-button>
            <a-button type="primary" size="small" @click="save">确定</a-button>
          </footer>
        </div>
      </a-spin>
    </template>
  </a-popover>
</template>
<style lang="less">
.setting-container {
  .ant-popover-content {
    .ant-popover-arrow {
      display: none;
    }
  }
}
</style>
<style lang="less" scoped>
.button {
  display: flex;
  align-items: center;
  height: 30px;
  border-radius: 100px;
  background: #1d2865;
  padding: 4px 8px 4px 12px;
  color: var(--unnamed, #fff);
}

.setting {
  min-width: 620px;
  height: 408px;
  border-radius: 8px;
  background: #1d2865;
  header {
    padding: 0 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 36px;
    background: #1d2865;
    :deep(.ant-picker) {
      width: 70px;
      background-color: #28357c;
      height: 26px;
    }
    .title {
      color: #fff;
      /* 文字/05副标题-常规Regular */
      font-family: Alibaba PuHuiTi 2;
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      line-height: 22px; /* 157.143% */
    }
    .right {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }
  main {
    height: 336px;
    display: flex;
    .title {
      padding: 0 12px;
      height: 32px;
      background: #131e5b;
      color: #5b6ccc;
      /* 文字/07内文-文本Regular */
      font-family: Alibaba PuHuiTi 2;
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
      line-height: 32px; /* 183.333% */
    }
    .sticky {
      position: sticky;
      top: 0;
      z-index: 1;
    }
    .add-user {
      height: 100%;
      min-width: 148px;
      border-right: 1px solid #1b3b61;
      overflow: auto;
    }
    .target-setting {
      flex: 1;
      height: 100%;
      overflow: auto;
    }
    .item {
      height: 32px;
      padding: 4px 16px;
      background-color: #1d2865;
    }
    .list {
      display: flex;
      flex-direction: column;
      padding: 0 8px 0 16px;
      &.add-list {
        padding: 0;
        :deep(.ant-checkbox-wrapper) {
          padding: 0 8px 0 16px;
        }
      }
      .header-title {
        color: #b7c2ff;
        /* 文字/07内文-文本Regular */
        font-family: 'Alibaba PuHuiTi 2.0';
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: 22px; /* 183.333% */
        &.item {
          background: #101b59;
        }
      }
      .target-item {
        height: 32px;
        padding: 4px 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        &:hover {
          background-color: #28357c;
          .setting-delete {
            display: inline-block;
          }
        }
        .setting-delete {
          display: none;
          cursor: pointer;
        }
        .label-target {
          display: flex;
          align-items: center;
        }
        .label {
          width: 80px;
          margin-right: 12px;
          color: #fff;
          /* 文字/07内文-文本Regular */
          font-family: Alibaba PuHuiTi 2;
          font-size: 12px;
          font-style: normal;
          font-weight: 400;
          line-height: 22px; /* 183.333% */
        }
        input {
          width: 160px;
        }
      }
    }
  }
  footer {
    padding: 0 12px;
    height: 36px;
    border-top: 1px solid #1b3b61;
    background: #1d2865;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 4px;
    :deep(.ant-btn-default) {
      border-radius: 4px;
      background: rgba(21, 73, 255, 0.2);
      border: none;
    }
  }
}
</style>
